<?php

namespace Tools\Utils;

use think\File;

class Images
{
    /**
     * 获取图片转为base64
     * @param string $avatar
     * @return bool|string
     */
    public static function image_to_base64($avatar = '', $timeout = 9)
    {
        $avatar = str_replace('https', 'http', $avatar);
        try {
            $url = parse_url($avatar);
            $url = $url['host'];
            $header = [
                'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
                'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                'Accept-Encoding: gzip, deflate, br',
                'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Host:' . $url
            ];
            $dir = pathinfo($url);
            $host = $dir['dirname'];
            $refer = $host . '/';
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_REFERER, $refer);
            curl_setopt($curl, CURLOPT_URL, $avatar);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            $data = curl_exec($curl);
            $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);
            if ($code == 200) {
                return "data:image/jpeg;base64," . base64_encode($data);
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取图片转为base64
     * @param string $avatar
     * @return bool|string
     */
    public static function put_image($url, $filename = '')
    {

        if ($url == '') {
            return false;
        }
        try {
            if ($filename == '') {

                $ext = pathinfo($url);
                if ($ext['extension'] != "jpg" && $ext['extension'] != "png" && $ext['extension'] != "jpeg") {
                    return false;
                }
                $filename = time() . "." . $ext['extension'];
            }

            //文件保存路径
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
            $path = 'uploads/qrcode';
            $fp2 = fopen($path . '/' . $filename, 'a');
            fwrite($fp2, $img);
            fclose($fp2);
            return $path . '/' . $filename;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 合并图片
     * @param string $fileName
     * @param File $dst_im
     * @param File $src_im
     * @param int $dst_x
     * @param int $dst_y
     * @param int $src_x
     * @param int $src_y
     * @param int $pc
     * @return string
     */
    public static function mergeImg(string $fileName, File $dst_im, File $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $pc = 100): string
    {
        $image_1 = imagecreatefrompng($dst_im->getPath() . DIRECTORY_SEPARATOR . $dst_im->getFilename());
        $image_2 = imagecreatefrompng($src_im->getPath() . DIRECTORY_SEPARATOR . $src_im->getFilename());

        $src_w = imagesx($image_2);
        $src_h = imagesy($image_2);

        imagecopymerge($image_1, $image_2, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pc);
        imagepng($image_1, $fileName);
        return $fileName;
    }

    /**
     * 获取图片base64str
     * @param $img_file
     * @return string
     */
    public static function imgToBase64($img_file): string
    {
        $imgBase64 = '';
        if (file_exists($img_file)) {
            $appImgFile = $img_file; // 图片路径
            $imgInfo = getimagesize($appImgFile); // 取得图片的大小，类型等

            $fp = fopen($appImgFile, "r"); // 图片是否可读权限
            if ($fp) {
                $fileSize = filesize($appImgFile);
                $content = fread($fp, 2 * $fileSize);//不知道为什么要加个2，不加图片只有一半
                $fileContent = chunk_split(base64_encode($content)); // base64编码
                switch ($imgInfo[2]) { //判读图片类型
                    case 1:
                        $imgType = "gif";
                        break;
                    case 2:
                        $imgType = "jpg";
                        break;
                    case 3:
                        $imgType = "png";
                        break;
                    default:
                        $imgType = "png";
                }

                $imgBase64 = 'data:image/' . $imgType . ';base64,' . $fileContent;//合成图片的base64编码
            }
            fclose($fp);
        }

        return $imgBase64; //返回图片的base64
    }
}
